package com.handpay.nocardpay.baselibrary.download.widget;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.util.Log;

import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.download.view.activity.DownloadApkActivity;
import com.handpay.nocardpay.baselibrary.http.SSLCustomSocketFactory;
import com.handpay.nocardpay.baselibrary.logutils.HPLog;
import com.nostra13.universalimageloader.utils.StorageUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class DownloadService extends IntentService {

    static final String APK_DOWNLOAD_URL = "url";
    static final String KEY_MESSAGE = "KEY_MESSAGE";
    private static final int BUFFER_SIZE = 10 * 1024; // 8k ~ 32K
    private static final String TAG = "DownloadService";

    private static final int NOTIFICATION_ID = 0;

    private NotificationManager mNotifyManager;
    private Builder mBuilder;

    public DownloadService() {
        super("DownloadService");
        HPLog.i(HPLog.YL_TAG, "DownloadService:");

    }


    @Override
    protected void onHandleIntent(Intent intent) {
        mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(this);
        String appName = getString(getApplicationInfo().labelRes);
        int icon = getApplicationInfo().icon;
        mBuilder.setContentTitle(appName).setSmallIcon(icon);
        String urlStr = intent.getStringExtra(APK_DOWNLOAD_URL);
        Messenger messenger = (Messenger) intent.getExtras().get(KEY_MESSAGE);
        InputStream in = null;
        FileOutputStream out = null;
        try {
            long bytetotal =0;
            long bytesum = 0;
            int byteread = 0;

            if (urlStr.startsWith("https://")){
                InputStream keyStore = getResources().openRawResource(R.raw.handpaydownlad);
                URL url = new URL(urlStr);
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
                httpsURLConnection.setSSLSocketFactory(SSLCustomSocketFactory.getSocketFactory(keyStore, "handpay"));
                // 读取超时时间 毫秒级
                httpsURLConnection.setReadTimeout(10000);
                httpsURLConnection.setRequestMethod("GET");
                httpsURLConnection.setDoInput(true);
                httpsURLConnection.connect();
                bytetotal = httpsURLConnection.getContentLength();
                bytesum = 0;
                byteread = 0;
                in = httpsURLConnection.getInputStream();
            }else {
                URL url = new URL(urlStr);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                // 读取超时时间 毫秒级
                httpURLConnection.setReadTimeout(10000);
                httpURLConnection.setRequestMethod("GET");
                httpURLConnection.setDoInput(true);
                httpURLConnection.connect();
                bytetotal = httpURLConnection.getContentLength();
                bytesum = 0;
                byteread = 0;
                in = httpURLConnection.getInputStream();
            }
            File dir = StorageUtils.getCacheDirectory(this);
            String apkName = urlStr.substring(urlStr.lastIndexOf("/") + 1, urlStr.length());
            File apkFile = new File(dir, apkName);
            out = new FileOutputStream(apkFile);
            byte[] buffer = new byte[BUFFER_SIZE];
            int oldProgress = 0;
            while ((byteread = in.read(buffer)) != -1) {
                bytesum += byteread;
                out.write(buffer, 0, byteread);
                int progress = (int) (bytesum * 100L / bytetotal);
                if (progress != oldProgress) {
                    Message message = Message.obtain();
                    message.what = DownloadApkActivity.MSG_DOWNING;
                    message.arg1 = progress;
                    messenger.send(message);
                    updateProgress(progress);
                }
                oldProgress = progress;
            }
            // 下载完成
            Message message = Message.obtain();
            message.what = DownloadApkActivity.MSG_FINISH;
            messenger.send(message);
            installAPk(apkFile);
            mNotifyManager.cancel(NOTIFICATION_ID);
        } catch (Exception e) {
            try {
                Message message = Message.obtain();
                message.what = DownloadApkActivity.MSG_FAILURE;
                messenger.send(message);
            } catch (RemoteException re) {
                re.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();

                }
            }
        }
    }

    private void updateProgress(int progress) {
        //"正在下载:" + progress + "%"
        mBuilder.setContentText(this.getString(R.string.android_auto_update_download_progress, progress)).setProgress(100, progress, false);
        //setContentInent如果不设置在4.0+上没有问题，在4.0以下会报异常
        PendingIntent pendingintent = PendingIntent.getActivity(this, 0, new Intent(), PendingIntent.FLAG_CANCEL_CURRENT);
        mBuilder.setContentIntent(pendingintent);
        mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
    }


    private void installAPk(File apkFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //如果没有设置SDCard写权限，或者没有sdcard,apk文件保存在内存中，需要授予权限才能安装
        try {
            String[] command = {"chmod", "777", apkFile.toString()};
            ProcessBuilder builder = new ProcessBuilder(command);
            builder.start();
        } catch (IOException ignored) {
        }
        intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}
